import { Component, OnInit, Input, Output, EventEmitter, ElementRef, SimpleChanges} from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../smartadmin.config';
import { Router } from "@angular/router";

declare var $: any;
var pinyin = require("pinyin");
@Component({
	selector: 'sa-tree-checkbox',
	templateUrl: './treeCheckbox.component.html',
	styleUrls: ['./treeCheckbox.component.css'],
})
export class TreeCheckboxComponent implements OnInit {
	@Input() htmlTreeId: string; //树的标识Id
	@Input() wrap: any; //事件页面根元素
	@Input() wrapId: any; //事件页面根元素Id
	@Input() dataValue: any; //绑定名称[name,id]
	@Input() Height: number; //高度
	@Input() inputName: string = 'name'; //校验使用的名称;默认name="name"
	@Input() placeholder: string = '请选择'; //弱提示语
	@Input() inputParam: any = {}; //接口参数
	@Output() selectedValue = new EventEmitter();
	private selectedNameList: any = []; //选中的名称(多选)
	private selectedIdList: any = []; //选中的ID(多选)
	private selectedList: any = []; //选中的数据obj(多选)
	private dataList: any = carTypeListObj.carTypeListTree; //全部数据
	clearTimer: any = '' // 定时器id
	constructor(private jsonApiService: JsonApiService, private el: ElementRef, private router: Router) {}
	//传参给父组件
	sendParent() {
		let dataInfo = {
			'dataList': this.dataList,
			'selectedNameList': this.selectedNameList,
			'selectedIdList': this.selectedIdList,
			'selectedList': this.selectedList,
		}
		this.selectedValue.emit(dataInfo);
	}
	ngOnInit() {
		// System.import('assets/js/jstree/jstree.min.js').then(() => {
		// 	this.initDataList();
		// 	this.treeCilckEvent();
		// })
	}
	ngOnChanges(changes: SimpleChanges) {
		if(this.dataValue && this.dataValue.length > 0) {
			this.selectedNameList = [];
			this.selectedIdList = [];
			this.selectedList = [];
			for(let item of this.dataValue) {
				this.selectedNameList.push(item.text);
				this.selectedIdList.push(item.id);
			}
			this.selectedList = this.dataValue;
			$('#' + this.htmlTreeId).find('.tree__input').val(this.selectedNameList.join(',')).change();
			this.sendParent();
		} else {
			this.selectedNameList = [];
			this.selectedIdList = [];
			this.selectedList = [];
			$('#' + this.htmlTreeId).find('.tree__input').val('')
			this.sendParent();
		}
	}
	//页面点击事件监听
	treeCilckEvent() {
		let htmlTreeId = document.getElementById(this.htmlTreeId);
		let tree_box = htmlTreeId.getElementsByClassName('s_tree_box')[0];
		let treeInput = htmlTreeId.getElementsByClassName('tree__input')[0];
		let wrap;
		if(this.wrapId){
			wrap = document.getElementById(this.wrapId)
		}else{
			if(this.wrap == 'body') {
				wrap = document.getElementsByTagName('body')[0];
			} else if(this.wrap == 'html') {
				wrap = document.getElementsByTagName('html')[0];
			} else {
				wrap = document;
			}
		}
		wrap.onclick = null;
		wrap.onclick = function(e: any) {
			if(tree_box.contains(e.target) || e.target == treeInput) { //判断点击是否在下拉框内
				// 如果确认按钮-关闭
				if(e.target.className == 'btn btn-primary'){ 
					tree_box.className = tree_box.className.replace("tree_open", "");
				}
			} else { 
				tree_box.className = tree_box.className.replace("tree_open", "");
				$('#' + this.htmlTreeId).find('.treeSearchInput').val('')
			}
			
		}.bind(this)
	}
	ngOnDestroy() {
		let wrap:any = this.wrapId?document.getElementById(this.wrapId):(this.wrap ? document.getElementsByTagName(this.wrap) : document);;
		wrap.onclick = null;
	}
	// 渲染数据
	reloadJsTree(type){
		if (type == 'load') { // 渲染勾选项
			// $('#' + this.htmlTreeId).jstree("uncheck_all")
			if(this.selectedIdList.length) {
				this.resetSlect()
				for(let lis of this.selectedIdList){
					this.dataSetSelected(lis, this.dataList)
				}
			}else {
				this.resetSlect()
			}
		} else if (type == 'reset') {   // 清空勾选项
			this.resetSlect()
		}
	}
	resetSlect() {
		for(let item of this.dataList){
			item.state.selected = false;
			if(item.children){
				for(let ele of item.children){
					ele.state.selected = false;
				}
			}
		}
	}
	dataSetSelected(id, arr) {
		for(let ele of arr || []) {
			if(ele.id == id) {
				if(ele.id.length != 2){
					ele.state.selected = true;
				}
				return true;
			}
			const o_ = this.dataSetSelected(id, ele.children)
			if(o_) return true;
		}
	}
	//拉取公司数据,生成树形图
	initDataList(type) {
		// 是否之前选中
		this.reloadJsTree(type)
		// 销毁 jsTree
		$('#' + this.htmlTreeId).find('.treeId').eq(0).jstree("destroy");
		$('#' + this.htmlTreeId).find('.treeId').eq(0).data('jstree', false).empty().jstree({
			"core": {
				'data': this.dataList,
				"themes": {
					"responsive": true
				},
				"multiple": true,
				"animation": 100,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"checkbox": {
				"keep_selected_style": false,
				"three_state": true, //父子级别级联选择
			},
			"types" : {
				"default" : {
					"icon" : "fa  fa-automobile"
				}
			},
			"plugins": ["search","checkbox","types"]
		})
	}
	// 确认所选值
	submitTreeValue() {
		var tree = $('#' + this.htmlTreeId).find('.treeId').eq(0).jstree();
		var selectedIds = tree.get_checked();   //获取所有选中节点id
		var selected = tree.get_checked(true);  //获取所有选中节点数据
		console.log(selected, 'selected', tree.get_top_selected(true))
		this.selectedList = [];
		this.selectedNameList = [];
		this.selectedIdList = [];
		for(let item of selected){
			let obj = {
				id:item.id,
				text:item.text // 获取内容前删除添加的拼音字段
			}
			this.selectedNameList.push(item.text);
			this.selectedIdList.push(item.id);
			this.selectedList.push(obj);
		}
		var that = this;
		$.each($('#' + this.htmlTreeId).jstree("get_undetermined").find(".jstree-undetermined"), function (index, item) {
			let id = item.closest(".jstree-node").id;
			let curItem = that.dataList.find(ele => ele.id == id);
			that.selectedNameList.push(curItem.text);
			that.selectedIdList.push(id);
			that.selectedList.push({id: id, text: curItem.text});
		})
		$('#' + this.htmlTreeId).find('.tree__input').val(this.selectedNameList.join(',')).change();
		this.sendParent();
	}
	// 重置[清空选值]
	resetTreeValue() {
		this.initDataList('reset');
	}
	//擦除公司所选值
	delText() {
		this.selectedNameList = [];
		this.selectedIdList = [];
		this.selectedList = [];
		$('#' + this.htmlTreeId).find('.tree__input').val("").change();
		this.treeSearch();
		if($('#' + this.htmlTreeId).find('.s_tree_box')[0].className.indexOf('tree_open') > 0) {
			$('#' + this.htmlTreeId).find('.tree__input').focus();
		}
		this.sendParent()
	}
	//打开公司树
	openTreeClick(e) {
		var treeBox = $('.s_tree_box');
		for (var i = 0; i < treeBox.length; i++) {
			if(e.target.parentNode.parentNode.parentNode.id != this.htmlTreeId){
				treeBox[i].className = treeBox[i].className.replace("tree_open", "");
			}
		}
		if($('#' + this.htmlTreeId).find('.s_tree_box')[0].className.indexOf('tree_open') < 0) {
			System.import('assets/js/jstree/jstree.min.js').then(() => {
				this.initDataList('load');
				this.treeCilckEvent();
			})
		}
		$('#' + this.htmlTreeId).find('.s_tree_box').toggleClass('tree_open');
		$('#' + this.htmlTreeId).find('.treeSearchInput').val('');
	}
	//公司树模糊搜索
	treeSearch() {
		var that = this;
		var value = $('#' + this.htmlTreeId).find('.treeSearchInput').val();
		if(this.clearTimer) { clearTimeout(this.clearTimer); }
		this.clearTimer = setTimeout(function () {
			$('#' + that.htmlTreeId).find('.treeId').eq(0).jstree(true).search(value);
			let searchResult = $('#' + that.htmlTreeId).find('.jstree-search').length;
			if(searchResult < 1) {
				return;
			}
			$('#' + that.htmlTreeId).find('.jstree-search').each(function(index, obj) {
				if(index < 1) { //js树搜索定位到结果的第一个地方；
					let container = $('#' + that.htmlTreeId).find('.vision_tree');
					let scrollTo = $(this);
					container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
					container.animate({
						scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
					});
				}
			})
		},250)
	}
	//公司树模糊搜索	click
	treeSearchBtn() {
		var that = this;
		var value = $('#' + this.htmlTreeId).find('.treeSearchInput').val();
		$('#' + this.htmlTreeId).find('.treeId').eq(0).jstree(true).search(value);
		let searchResult = $('#' + this.htmlTreeId).find('.jstree-search').length;
		if(searchResult < 1) {
			that.jsonApiService.message('未搜索到结果');
			return;
		}
		$('#' + this.htmlTreeId).find('.jstree-search').each(function(index, obj) {
			if(index < 1) { //js树搜索定位到结果的第一个地方；
				let container = $('#' + that.htmlTreeId).find('.vision_tree');
				let scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
				});
			}
		})
	}
}